package com.base.mine;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.design.widget.AppBarLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.base.commonlib.base.BaseApp;
import com.base.commonlib.base.CBaseBarMvpActivity;
import com.base.commonlib.bean.User;
import com.base.commonlib.event.AddressEvent;
import com.base.commonlib.event.ImagePath;
import com.base.commonlib.sp.SpUtil;
import com.base.commonlib.utils.GlideUtil;
import com.base.commonlib.utils.RxBus2;
import com.base.commonlib.widget.AnimUtil;
import com.base.commonlib.widget.KeyboardWatcher;
import com.base.commonlib.widget.PhotoSelectManager;
import com.base.mine.databinding.ActivityAccountprivactBinding;
import com.base.mine.presenter.AccountPrivacyPresenter;
import com.base.mine.view.AccountPrivacyView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 账户及隐私
 * Created by weikailiang on 2020/3/18.
 */
@Route(path = "/mine/accountprivacy")
public class AccountPrivacyActivity extends CBaseBarMvpActivity<AccountPrivacyPresenter> implements AccountPrivacyView,KeyboardWatcher.SoftKeyboardStateListener{
    private static final int CAMERA_RESULT = 100;
    private static final int PHOTO_CUT = 102;
    private static final int PHOTO_RESULT = 101;


    private static final int CAMERA_RESULT_BG = 103;
    private static final int PHOTO_CUT_BG = 104;
    private static final int PHOTO_RESULT_BG = 105;
    private KeyboardWatcher keyboardWatcher;
    private float scale = 0.8f;
    private ActivityAccountprivactBinding mBinding;
    @Override
    protected int getLayoutResource() {
        return R.layout.activity_accountprivact;
    }

    @Override
    protected void init() {
        super.init();
        mBinding = (ActivityAccountprivactBinding) mRootBinding;
        mPresenter = new AccountPrivacyPresenter(this,this);
        mPresenter.start();
        if (!TextUtils.isEmpty(SpUtil.getCenterImg())){
            Bitmap bitmap = getLoacalBitmap(SpUtil.getCenterImg()); //从本地取图片(在cdcard中获取)  //
            mBinding.newsDetailPhotoIv.setImageBitmap(bitmap); //设置Bitmap
        }else {
            mBinding.newsDetailPhotoIv.setImageResource(R.mipmap.ic_bg_time);
        }
        if (mPresenter.mUser!=null){
            if (!TextUtils.isEmpty(mPresenter.mUser.getAvatar())){
                GlideUtil.load(mContext,mPresenter.mUser.getAvatar(),mBinding.fab);
            }else {
                mBinding.fab.setImageResource(R.mipmap.ic_default_img);
            }
        }else {
            mBinding.fab.setImageResource(R.mipmap.ic_default_img);
        }
    }

    @Override
    protected void start() {
        mBinding.toolbarLayout.setTitle("个人中心");
        mBinding.toolbarLayout.setExpandedTitleColor(ContextCompat.getColor(this, R.color.color_white));
        mBinding.toolbarLayout.setCollapsedTitleTextColor(ContextCompat.getColor(this, R.color.color_white));


        mBinding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    finishAfterTransition();
                } else {
                    finish();
                }
            }
        });
        mBinding.appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset<=-542){
                    mBinding.fab.setVisibility(View.GONE);
                }else {
                    if (mBinding.fab.getVisibility()!=View.VISIBLE){
                        mBinding.fab.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
//        mBinding.toolbar.inflateMenu(R.menu.news_detail);
//        mBinding.toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
//            @Override
//            public boolean onMenuItemClick(MenuItem item) {
//                int i = item.getItemId();
//                if (i == R.id.action_web_view) {
//                    ARouter.getInstance().build("/home/pahtview").withString("type","1").navigation();
//                } else if (i == R.id.action_browser) {
//                    ARouter.getInstance().build("/home/pahtview").withString("type","2").navigation();
//                }
//
//                return true;
//            }
//        });

        mBinding.rlMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ARouter.getInstance().build("/mine/morecenterintro").navigation();
            }
        });
        //分享

        mBinding.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PhotoSelectManager.getmInstance().show(AccountPrivacyActivity.this, new PhotoSelectManager.popListener() {
                    @Override
                    public void cameraClick(TextView camera) {
                        Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(in, CAMERA_RESULT);
                        PhotoSelectManager.getmInstance().dismiss();
                    }

                    @Override
                    public void albumClick(TextView photos) {
                        Intent in = new Intent(Intent.ACTION_PICK);
                        in.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(in, PHOTO_RESULT);
                        PhotoSelectManager.getmInstance().dismiss();
                    }

                    @Override
                    public void cancelClick(TextView cacel) {
                        PhotoSelectManager.getmInstance().dismiss();
                    }
                });
            }
        });
        mBinding.newsDetailPhotoIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PhotoSelectManager.getmInstance().show(AccountPrivacyActivity.this, new PhotoSelectManager.popListener() {
                    @Override
                    public void cameraClick(TextView camera) {
                        Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(in, CAMERA_RESULT_BG);
                        PhotoSelectManager.getmInstance().dismiss();
                    }

                    @Override
                    public void albumClick(TextView photos) {
                        Intent in = new Intent(Intent.ACTION_PICK);
                        in.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(in, PHOTO_RESULT_BG);
                        PhotoSelectManager.getmInstance().dismiss();
                    }

                    @Override
                    public void cancelClick(TextView cacel) {
                        PhotoSelectManager.getmInstance().dismiss();
                    }
                });
            }
        });
        keyboardWatcher = new KeyboardWatcher(findViewById(Window.ID_ANDROID_CONTENT));
        keyboardWatcher.addSoftKeyboardStateListener(this);


        Disposable disposable = RxBus2.getInstance().doSubscribe(ImagePath.class, new Consumer<ImagePath>() {
            @Override
            public void accept(ImagePath imagePath) throws Exception {
               if (imagePath.getType().equals("1")){
                   Bitmap bitmap = getLoacalBitmap(imagePath.getPath()); //从本地取图片(在cdcard中获取)  //
                   mBinding.newsDetailPhotoIv.setImageBitmap(bitmap); //设置Bitmap
                   SpUtil.setCenterImg(imagePath.getPath());
               }else if (imagePath.getType().equals("2")){
                   mPresenter.upPicPhoto(imagePath.getPath());
               }

            }
        });
        RxBus2.getInstance().addSubscription(this, disposable);
        Disposable disposable1 = RxBus2.getInstance().doSubscribe(User.class, new Consumer<User>() {
            @Override
            public void accept(User user) throws Exception {
                mBinding.userNick.setText(user.getUserName());
                mBinding.userOrign.setText(user.getOrgName());
                mBinding.userPhone.setText(user.getPhone().substring(0,3)+"****"+user.getPhone().substring(user.getPhone().length()-4,user.getPhone().length()));
                mBinding.userRealname.setText(user.getRealName());
            }
        });
        RxBus2.getInstance().addSubscription(this, disposable1);


        if (mPresenter.mUser!=null){
            mBinding.userNick.setText(mPresenter.mUser.getUserName());
            mBinding.userOrign.setText(mPresenter.mUser.getOrgName());
           mBinding.userOrign.setText(mPresenter.mUser.getDeptName());
            mBinding.userPhone.setText(mPresenter.mUser.getPhone().substring(0,3)+"****"+mPresenter.mUser.getPhone().substring(mPresenter.mUser.getPhone().length()-4,mPresenter.mUser.getPhone().length()));
            mBinding.userRealname.setText(mPresenter.mUser.getRealName());
        }


        mBinding.rlRealname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ARouter.getInstance().build("/mine/modifyusername")
                        .withString("title","修改真实姓名")
                        .withString("name",mPresenter.mUser.getRealName())
                        .withInt("type",2).navigation();
            }
        });
        mBinding.rlUsername.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ARouter.getInstance().build("/mine/modifyusername")
                        .withString("title","修改用户昵称")
                        .withString("name",TextUtils.isEmpty(mPresenter.mUser.getUserName())?"":mPresenter.mUser.getUserName())
                        .withInt("type",1).navigation();
            }
        });
        mBinding.chargepwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ARouter.getInstance().build("/changepw/pw")
                       .navigation();
            }
        });



    }




    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case CAMERA_RESULT:
                if (resultCode == RESULT_OK && null != data) {
                    String sdState = Environment.getExternalStorageState();
                    if (!sdState.equals(Environment.MEDIA_MOUNTED)) {
                        return;
                    }
                    String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
                    Bundle bundle = data.getExtras();
                    Bitmap bitmap = (Bitmap) bundle.get("data");
                    File file = new File("/sdcard/yookey/photo/");
                    if (!file.isDirectory()) {
                        file.mkdirs();
                    }
                    String filename = file.getPath() + "/" + name;
                    FileOutputStream fout = null;
                    try {
                        fout = new FileOutputStream(filename);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            fout.flush();
                            fout.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    startPhotoZoom(Uri.fromFile(new File(filename)));
                }
                break;
            case PHOTO_RESULT:
                if (resultCode == RESULT_OK && null != data) {
                    Uri u = data.getData();
                    if (u.getScheme().equals("content")) {
                        String[] project = new String[]{MediaStore.Images.Media.DATA};
                        Cursor c = getContentResolver().query(u, project, null, null, null);
                        if (c != null && c.moveToFirst()) {
                            //获取路径
                            String path = c.getString(c.getColumnIndex(project[0]));
                            startPhotoZoom(Uri.fromFile(new File(path)));
                        }
                    } else {
                        startPhotoZoom(data.getData());
                    }
                }
                break;
            case PHOTO_CUT:
                if (resultCode == RESULT_OK && null != data) {
//                    Bitmap bmp = data.getExtras().getParcelable("data");
                    Bitmap bmp = null;
                    try {
                        bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(upFileUri));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }

                    //裁剪图片保存
                    File file = new File("/sdcard/yookey/photo/");
                    if (!file.isDirectory()) {
                        file.mkdirs();
                    }
                    String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
                    String filename = file.getPath() + "/" + name;
                    FileOutputStream fout = null;
                    try {
                        fout = new FileOutputStream(filename);
                        bmp.compress(Bitmap.CompressFormat.JPEG, 100, fout);
                        mPresenter.upPicPhoto(filename);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                        showMes("图片保存失败");
                    } finally {
                        try {
                            fout.flush();
                            fout.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                            showMes("图片保存失败");
                        }
                    }
                }
                break;
            case CAMERA_RESULT_BG:
                if (resultCode == RESULT_OK && null != data) {
                    String sdState = Environment.getExternalStorageState();
                    if (!sdState.equals(Environment.MEDIA_MOUNTED)) {
                        return;
                    }
                    String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
                    Bundle bundle = data.getExtras();
                    Bitmap bitmap = (Bitmap) bundle.get("data");
                    File file = new File("/sdcard/yookey/photo/");
                    if (!file.isDirectory()) {
                        file.mkdirs();
                    }
                    String filename = file.getPath() + "/" + name;
                    FileOutputStream fout = null;
                    try {
                        fout = new FileOutputStream(filename);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            fout.flush();
                            fout.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    mBinding.newsDetailPhotoIv.setImageBitmap(bitmap); //设置Bitmap
                    SpUtil.setCenterImg(filename);
//                    GlideUtil.loadFile(mContext,filename,mBinding.newsDetailPhotoIv);
//                    startPhotoZoomBg(Uri.fromFile(new File(filename)));
                }
                break;
            case PHOTO_RESULT_BG:
                if (resultCode == RESULT_OK && null != data) {
                    Uri u = data.getData();
                    if (u.getScheme().equals("content")) {
                        String[] project = new String[]{MediaStore.Images.Media.DATA};
                        Cursor c = getContentResolver().query(u, project, null, null, null);
                        if (c != null && c.moveToFirst()) {
                            //获取路径
                            String path = c.getString(c.getColumnIndex(project[0]));

                            Bitmap bitmap = getLoacalBitmap(path); //从本地取图片(在cdcard中获取)  //
                            mBinding.newsDetailPhotoIv.setImageBitmap(bitmap); //设置Bitmap
                            SpUtil.setCenterImg(path);
//                            GlideUtil.loadFile(mContext,path,mBinding.newsDetailPhotoIv);
//                            startPhotoZoomBg(Uri.fromFile(new File(path)));
                        }
                    } else {
                        Bitmap bitmap = getLoacalBitmap(data.getData().getPath()); //从本地取图片(在cdcard中获取)  //
                        mBinding.newsDetailPhotoIv.setImageBitmap(bitmap); //设置Bitmap
                        SpUtil.setCenterImg(data.getData().getPath());
//                        GlideUtil.loadFile(mContext,data.getData().getPath(),mBinding.newsDetailPhotoIv);
//                        startPhotoZoomBg(data.getData());
                    }
                }
                break;
        }
    }
    /**
     * 加载本地图片
     * @param url
     * @return
     */
    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
    private Uri upFileUri;
    //裁剪图片
    private void startPhotoZoom(Uri uri) {
        if (uri == null){
            Log.i("PersonCenterActivity","the uri is null...");
            return;
        }

        upFileUri = uri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
//        intent.putExtra("return-data", true);
        /**
         * 此方法返回的图片只能是小图片（sumsang测试为高宽160px的图片）
         * 故将图片保存在Uri中，调用时将Uri转换为Bitmap，此方法还可解决miui系统不能return data的问题
         */
        //intent.putExtra("return-data", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        startActivityForResult(intent, PHOTO_CUT);



//        startActivityForResult(intent, PHOTO_CUT);
    }


    @Override
    public void onSoftKeyboardOpened(int keyboardSize) {
        int[] location = new int[2];
        mBinding.nsvScroller.getLocationOnScreen(location);
        int x = location[0];
        int y = location[1];
        int bottom = BaseApp.SCREEN_HEIGHT - (y +  mBinding.nsvScroller.getHeight());
        if (keyboardSize > bottom) {
            ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat( mBinding.nsvScroller, "translationY", 0.0f, -(keyboardSize - bottom));
            mAnimatorTranslateY.setDuration(300);
            mAnimatorTranslateY.setInterpolator(new AccelerateDecelerateInterpolator());
            mAnimatorTranslateY.start();
            AnimUtil.zoomIn(mBinding.fab, keyboardSize - bottom, scale);
        }
    }

    @Override
    public void onSoftKeyboardClosed() {
        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(mBinding.nsvScroller, "translationY", mBinding.nsvScroller.getTranslationY(), 0);
        mAnimatorTranslateY.setDuration(300);
        mAnimatorTranslateY.setInterpolator(new AccelerateDecelerateInterpolator());
        mAnimatorTranslateY.start();
        AnimUtil.zoomOut(mBinding.fab, scale);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        keyboardWatcher.removeSoftKeyboardStateListener(this);
    }

    @Override
    public void returnUpPhotoSuccess(String url) {
        GlideUtil.load(mContext,url,mBinding.fab);
    }
}
